<?php

/**
 * [PHPFOX_HEADER]
 */
defined('PHPFOX') or exit('No direct script access allowed.');

/**
 *
 *
 */
class Profiles_Service_Process extends Phpfox_Service {

	private $_bHasImage = false;

	/**
	 * Class constructor
	 */
	public function __construct()
	{
		$this->_sTable = Phpfox::getT('ko_profiles');

	}
    
    public function getUserNames($name){
        $user_id = Phpfox::getUserBy('user_id');
//        $rows = $this->database()->select('u.user_id id, u.full_name value, ISNULL(f.friend_id) as not_friend')
//            ->from(Phpfox::getT('user'), 'u')
//            ->leftJoin(Phpfox::getT('friend'), 'f', "u.user_id=f.friend_user_id and f.user_id='{$user_id}'")
//            ->where("u.full_name like '%{$name}%' and u.user_id<>".$user_id)
//            ->order("ISNULL(f.friend_id), u.full_name")
//            ->execute('getRows')
//        ;
        
        $rows = $this->database()->select('u.user_id id, u.full_name value, ISNULL(f.friend_id) as not_friend')
            ->from(Phpfox::getT('user'), 'u')
            ->leftJoin(Phpfox::getT('friend'), 'f', "u.user_id=f.friend_user_id and f.user_id='{$user_id}'")
            ->where("u.full_name like '%{$name}%' AND u.profile_page_id = 0 and u.user_id<>".$user_id)
            ->group("u.full_name")
            ->order("ISNULL(f.friend_id), u.full_name")
            ->execute('getRows')
        ;
//        $results = array();
        foreach($rows as $key => &$row){
            if($row['not_friend']){
                $row['type'] = 1;
            }else{
                $row['type'] = 0;
            }
            $row['id'] = $row['value'];
//            $results[] = $row;
//            if($key!=0 && $key!=(count($rows)-1) && $row['value'] == $rows[$key-1]['value'] && $row['value'] != $rows[$key+1]['value'] ){
//                $arr['id'] = "re_".$row['value'];
//                $arr['value'] = Phpfox::getPhrase('profiles.are_you_not_sure_about_the_results_found');
//                $arr['type'] = 1;
//                $results[] = $arr;
//            }
        }
		
		
        if($rows){
            $arr['value'] = '_______________________________';
            $rows[] = $arr; 
        }
		
		
		 // if(!$rows){
            $arr['id'] = $name;
            $arr['value'] = Phpfox::getPhrase('profiles.the_user_you_are_looking_for_is_not_register_into_the_site');
            $arr['type'] = 2;
            $rows[] = $arr; 
        // }
//        return $results;
        return $rows;
		
		
		
    }
    private function checkEmail($aVals){
        if($aVals['user_id']>0){
            $row = $this->getUserById($aVals['user_id']);
            if($row['email'] != $aVals['email'] && $row['not_friend']=='1')
            {
                $row = false;
            }
        }elseif($aVals['user_id']=='-1'){
            $row['email'] = $aVals['email'];
        }else{
            $row = false;
        }
        return $row;
    }
//    public function addFeed($notification){
//        $content = $this->getInviteMessage($notification['notification_id']);
//        
//        $sql = array('user_id'=>$notification['user_id'], 'content'=>$content, 'time_stamp'=>PHPFOX_TIME);
//        $inserted_id = $this->database()->insert(Phpfox::getT('user_status'), $sql);
//        $sql = array('type_id'=>'user_status', 'user_id'=>$notification['user_id'], 'item_id'=>$inserted_id, 'time_stamp'=>PHPFOX_TIME, 'time_update'=>PHPFOX_TIME);
//        $inserted_id = $this->database()->insert(Phpfox::getT('feed'), $sql);
//    }
    public function addFeed($notification){
        $content = $this->getInviteMessage($notification['notification_id']);
        $content .= "<br>".nl2br($message);
        $receiver = $this->database()->select("*")
            ->from(Phpfox::getT('profiles_user'))
            ->where('id='.$notification['item_id'])
            ->execute('getRow');
        $content .= "<br>".nl2br($receiver['message']);
        
        $user = Phpfox::getUserBy();
        
        $sql = array('user_id'=>$user['user_id'], 'content'=>$content, 'privacy'=>1, 'time_stamp'=>PHPFOX_TIME);
        $inserted_id = $this->database()->insert(Phpfox::getT('user_status'), $sql);
        $sql = array('type_id'=>'user_status', 'user_id'=>$user['user_id'], 'privacy'=>1, 'item_id'=>$inserted_id, 'time_stamp'=>PHPFOX_TIME, 'time_update'=>PHPFOX_TIME);
        $inserted_id = $this->database()->insert(Phpfox::getT('feed'), $sql);
        
        $this->addProfilesFeedUser($inserted_id, $notification['owner_user_id']);

//        $sql = array('user_id'=>$notification['owner_user_id'], 'content'=>$content, 'privacy'=>3, 'time_stamp'=>PHPFOX_TIME);
//        $inserted_id = $this->database()->insert(Phpfox::getT('user_status'), $sql);
//        $sql = array('type_id'=>'user_status', 'user_id'=>$notification['owner_user_id'], 'privacy'=>3, 'item_id'=>$inserted_id, 'time_stamp'=>PHPFOX_TIME, 'time_update'=>PHPFOX_TIME);
//        $inserted_id = $this->database()->insert(Phpfox::getT('feed'), $sql);
    }
    
    private function addProfilesFeedUser($feed_id, $user_id){
        $this->database()->delete(Phpfox::getT('profiles_feed_user'),"feed_id='{$feed_id}'");
        $sql = array(
            'feed_id' => $feed_id,
            'user_id' => $user_id
        );
        $inserted_id = $this->database()->insert(Phpfox::getT('profiles_feed_user'), $sql);
        return $inserted_id;
    }

    public function addFeedForFriend($user, $message){
        $notification = $this->getNotification($nid);
        
        $receiver_id = $user['user_id'];
        $receiver = $this->getUser($receiver_id);
        $content = nl2br(Phpfox::getPhrase('profiles.anonymous_message',array('sender'=>Phpfox::getUserBy('full_name'), 'receiver'=>$receiver['full_name'])));
        $content .= "<br>".nl2br($message);
        
        $sql = array('user_id'=>$user['user_id'], 'content'=>$content, 'privacy'=>1, 'time_stamp'=>PHPFOX_TIME);
        $inserted_id = $this->database()->insert(Phpfox::getT('user_status'), $sql);
        $sql = array('type_id'=>'user_status', 'user_id'=>$user['user_id'], 'item_id'=>$inserted_id,'privacy'=>1, 'time_stamp'=>PHPFOX_TIME, 'time_update'=>PHPFOX_TIME);
        $inserted_id = $this->database()->insert(Phpfox::getT('feed'), $sql);

        $profilesFeedUserId = $this->addProfilesFeedUser($inserted_id, Phpfox::getUserBy('user_id'));
        return $profilesFeedUserId;
    
    }
    public function sendInvite($aVals){
        $user = $this->checkEmail($aVals);
        if(!$user){
            return Phpfox::getPhrase('profiles.not_match_mail_address');
        }
        switch($aVals['type']){
            /**
            * friend
            */
            case '0':
//                $mails['to'][0] = $user['user_id'];
//                $mails['subject'] = Phpfox::getPhrase('profiles.sent_message_him',array('sender'=>$user['full_name'], 'receiver'=>'you'));
//                $mails['message'] = $aVals['message'];
//                print_r($mails);exit;
//                Phpfox::getService('mail.process')->add($mails);
                $profilesFeedUserId = $this->addFeedForFriend($user, $aVals['message']);
                Phpfox::getService('notification.process')->add('profiles_invitefirendsforfriend', $profilesFeedUserId, $user['user_id'], Phpfox::getUserId());
//                Phpfox::getService('notification.process')->add('profiles_invitefirendsforfriend', 0, $user['user_id'], Phpfox::getUserId());
            break;
            /**
            * non-friend
            */
            case '1':
//                $mails['to'][0] = $user['user_id'];
//                $mails['subject'] = Phpfox::getPhrase('profiles.sent_message_him1',array('sender'=>$user['full_name'], 'receiver'=>'you'));
//                $mails['message'] = $aVals['message'];
//                Phpfox::getService('mail.process')->add($mails);
                $sql = array('email'=>$aVals['email'], 'username'=>$aVals['username'], 'message'=>$aVals['message']);
                $item_id = $this->database()->insert(Phpfox::getT('profiles_user'), $sql);
                Phpfox::getService('notification.process')->add('profiles_invitefirends', $item_id, $user['user_id'], Phpfox::getUserId());
            break;
            /**
            * no-user
            */
            case '2':
                $subject = Phpfox::getPhrase('profiles.subject4', array('sitename'=>Phpfox::getParam('core.global_site_title')));
                $message = Phpfox::getPhrase('profiles.a_person_has_sent_message_to_you')."<br>";
                $message .= Phpfox::getPhrase('profiles.site_service')."<br>";
                $mail = urlencode(base64_encode($aVals['email']));
                $sql = array('email'=>$aVals['email'], 'username'=>$aVals['username'], 'message'=>$aVals['message'], 'sender_id'=>Phpfox::getUserBy('user_id'));
                $item_id = $this->database()->insert(Phpfox::getT('profiles_user'), $sql);

                $accepturl = Phpfox::getLib('url')->makeUrl('profiles.manageinvite.'.Phpfox::getUserId().".{$item_id}.accept");
//                $refuseurl = Phpfox::getLib('url')->makeUrl('profiles.manageinvite.'.Phpfox::getUserId().".{$item_id}.refuse");
                $message .= Phpfox::getPhrase('profiles.accept_or_refuse', array('accepturl'=>$accepturl, 'refuseurl'=>''));
                $this->sendMail($aVals['email'], $subject, $message);
            break;
        }
        return false;
    }
    public function acceptNotification4($sender_id, $item_id){
        Phpfox::getService('notification.process')->add('profiles_acceptInvite', $item_id, $sender_id, $sender_id);
    }
    public function refuseNotification4($sender_id, $item_id){
        Phpfox::getService('notification.process')->add('profiles_refuseInvite', $item_id, $sender_id, $sender_id);
    }
    public function sendMail($email, $subject, $message){
//        $to      = $email;
//        $subject = $subject;
//        $message = $message;
//        $headers = 'From: messages@phpfox.com' . "\r\n" .
//            'Content-type: text/html; charset=iso-8859-1' . "\r\n".
//            'Reply-To: messages@phpfox.com' . "\r\n" .
//            'X-Mailer: PHP/' . phpversion();

//        mail($to, $subject, $message, $headers);

        Phpfox::getLib('mail')->to($email)
            // -> fromEmail(Phpfox::getUserBy('email'))
            //->fromName(Phpfox::getUserBy('full_name'))
            ->subject($subject) 
            ->message($message) 
            ->send();        
    }
    private function getNotification($id){
        $row = $this->database()->select("*")
            ->from(Phpfox::getT('notification'))
            ->where('notification_id='.$id)
            ->execute('getRow');
        return $row;
    }
    public function acceptInvite($aVals){
        $nid = $aVals['nid'];
        $notification = $this->getNotification($nid);
        if($aVals['accept']){
            $this->addFeed($notification);
            Phpfox::getService('notification.process')->add('profiles_acceptInvite1', $nid, $notification['owner_user_id'], $notification['user_id']);
//            Phpfox::getService('notification.process')->add('profiles_acceptInvite', 0, $notification['owner_user_id'], $notification['user_id']);
        }else{
            Phpfox::getService('notification.process')->add('profiles_refuseInvite1', $nid, $notification['owner_user_id'], $notification['user_id']);
//            Phpfox::getService('notification.process')->add('profiles_refuseInvite', 0, $notification['owner_user_id'], $notification['user_id']);
        }
        Phpfox::getService('notification.process')->delete('profiles_invitefirends', $notification['item_id'], Phpfox::getUserId());
    }
    public function getUser($user_id){
        $row = $this->database()->select("*")
            ->from(Phpfox::getT('user'))
            ->where('user_id='.$user_id)
            ->execute('getRow');
        return $row;
    }
    public function getInviteMessage($nid){
        $notification = $this->getNotification($nid);
        
        $receiver_id = $notification['user_id'];
        $receiver = $this->getUser($receiver_id);
        $sender_id = $notification['owner_user_id'];
        $sender = $this->getUser($sender_id);
        $content = Phpfox::getPhrase('profiles.anonymous_message',array('sender'=>$sender['full_name'], 'receiver'=>$receiver['full_name']));
        return $content;        
    }
    /**
    * ajax 2013/11/09
    */
    public function checkUsername($username){
        $user_id = Phpfox::getUserBy('user_id');
        $rows = $this->database()->select('u.*, ISNULL(f.friend_id) as not_friend')
            ->from(Phpfox::getT('user'), 'u')
            ->leftJoin(Phpfox::getT('friend'), 'f', "u.user_id=f.friend_user_id and f.user_id='{$user_id}'")
            ->where("u.full_name = '{$username}' and u.user_id<>".$user_id)
            ->execute('getRows')
        ;
        if(count($rows)>1){
            $message = "many_users";
        }elseif(count($rows) == 1 && $rows[0]['not_friend']){
            $user_id = $rows[0]['user_id'];
            $message = "no_friend";
        }elseif(count($rows) == 1 && !$rows[0]['not_friend']){
            $user_id = $rows[0]['user_id'];
            $message = "friend";
        }else{
            $message = "no_users";
        }
        $result['user_id'] = $user_id;
        $result['message'] = $message;
        return $result;
    }
    
    public function getUserById($user_id){
        $self_user_id = Phpfox::getUserBy('user_id');
        $row = $this->database()->select('u.*, ISNULL(f.friend_id) as not_friend')
            ->from(Phpfox::getT('user'), 'u')
            ->leftJoin(Phpfox::getT('friend'), 'f', "u.user_id=f.friend_user_id and f.user_id='{$self_user_id}'")
            ->where("u.user_id=".$user_id)
            ->execute('getRow')
        ;
        return $row;
    }
    
    public function setFeedOfNewuser($item_id, $receiver_id){
        $row = $this->database()->select("*")
            ->from(Phpfox::getT('profiles_user'))
            ->where("id='{$item_id}'")
            ->execute('getRow');
        $sender = $this->getUser($row['sender_id']);
        $receiver = $this->getUser($receiver_id);
        $content = Phpfox::getPhrase('profiles.anonymous_message',array('sender'=>$sender['full_name'], 'receiver'=>$receiver['full_name']));

        $content .= "<br><br>".$row['message'];
        $content = nl2br($content);
        
        $sql = array('user_id'=>$receiver['user_id'], 'content'=>$content, 'privacy'=>1, 'time_stamp'=>PHPFOX_TIME);
        $inserted_id = $this->database()->insert(Phpfox::getT('user_status'), $sql);
        $sql = array('type_id'=>'user_status', 'user_id'=>$receiver['user_id'], 'privacy'=>1, 'item_id'=>$inserted_id, 'time_stamp'=>PHPFOX_TIME, 'time_update'=>PHPFOX_TIME);
        $inserted_id = $this->database()->insert(Phpfox::getT('feed'), $sql);
        
        $profilesFeedUserId = $this->addProfilesFeedUser($inserted_id, $sender['user_id']);

        Phpfox::getService('notification.process')->add('profiles_registered', $profilesFeedUserId, $sender['user_id'], $receiver_id);

//        Phpfox::getService('notification.process')->add('profiles_registered', 0, $sender['user_id'], $receiver_id);
        Phpfox::setCookie('profiles_invite_itemid','', PHPFOX_TIME-3600);
//        $this->database->delete(Phpfox::getT('profiles_user'), 'id='.$item_id);
        
    }
}